package com.poetry.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poetry.domain.dto.CategoryDTO;
import com.poetry.domain.po.Category;
import com.poetry.exception.R;
import com.poetry.mapper.CategoryMapper;
import com.poetry.service.ICategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements ICategoryService {
    @Override
    @Transactional
    public R<String> updateProperties(CategoryDTO categoryDTO) {
        Category category = this.getById(categoryDTO.getId());
        if (category == null) {
            return R.error("类别不存在");
        }
        category.setName(categoryDTO.getName());
        boolean isSuccess = this.updateById(category);
        if (!isSuccess) {
            return R.error("更新失败");
        }
        return R.success(null, "动态属性修改成功");
    }

    @Override
    @Transactional
    public R<Category> addChildCategory(Integer parentId, Integer childId) {
        Category parent = this.getById(parentId);
        if (parent == null) {
            return R.error("类别不存在");
        }
        Category child = this.getById(childId);
        child.setParentId(parent.getId());
        child.setLevel(parent.getLevel() + 1);
        removeChildCategory(child, parentId);
        this.updateById(child);
        return R.success("类别层级更改成功", child);
    }

    @Transactional
    protected void removeChildCategory(Category child, Integer parentId) {
        List<Category> list = query().lambda().eq(Category::getParentId, child.getId()).list();
        list.forEach(e -> {
            e.setLevel(child.getLevel());
            e.setParentId(parentId);
        });
        updateBatchById(list);
    }

    @Override
    @Transactional
    public R<String> deleteCategory(Integer id) {
        Category category = this.getById(id);
        if (category == null) {
            return R.error("类别不存在");
        }
        Integer parentId = category.getParentId();
        if (parentId != null) {
            removeChildCategory(category, parentId);
        }
        boolean isSuccess = removeById(id);
        if (!isSuccess) {
            return R.error("删除失败");
        }
        return R.success(null,"删除类别成功");
    }

    @Override
    public R<List<Category>> getCategoryTree() {
        List<Category> allCategories = this.list();
        List<Category> tree = buildTree(allCategories);
        return R.success("分类树构建成功", tree);
    }

    private List<Category> buildTree(List<Category> categories) {
        // 构建树形结构（递归实现）
        Map<Integer, List<Category>> parentMap = new HashMap<>();
        for (Category cat : categories) {
            parentMap.computeIfAbsent(cat.getParentId(), k -> new ArrayList<>())
                    .add(cat);
        }

        List<Category> roots = parentMap.get(null);
        if (roots != null) {
            for (Category root : roots) {
                buildChildren(root, parentMap);
            }
        }
        return roots;
    }

    private void buildChildren(Category parent, Map<Integer, List<Category>> parentMap) {
        List<Category> children = parentMap.get(parent.getId());
        if (children != null) {
            parent.setChildren(children);
            for (Category child : children) {
                buildChildren(child, parentMap);
            }
        }
    }
}
